from rest_framework import serializers
from .models import Personnel, Equipment


class PersonnelSerializer(serializers.ModelSerializer):
    """
    人员信息序列化器
    用于处理Personnel模型的JSON序列化和反序列化
    """
    
    class Meta:
        model = Personnel
        fields = ['id', 'name', 'phone', 'group', 'created_at', 'updated_at']
        read_only_fields = ['id', 'created_at', 'updated_at']
    
    def validate_name(self, value):
        """
        验证姓名字段
        """
        if not value or not value.strip():
            raise serializers.ValidationError("姓名不能为空")
        return value.strip()
    
    def validate_group(self, value):
        """
        验证分组字段
        """
        if not value or not value.strip():
            raise serializers.ValidationError("分组不能为空")
        return value.strip()
    
    def validate_phone(self, value):
        """
        验证电话字段
        """
        if value:
            return value.strip()
        return value


class EquipmentSerializer(serializers.ModelSerializer):
    """
    设备信息序列化器
    用于处理Equipment模型的JSON序列化和反序列化
    """
    
    class Meta:
        model = Equipment
        fields = ['id', 'name', 'experiment', 'responsible', 'created_at', 'updated_at']
        read_only_fields = ['id', 'created_at', 'updated_at']
    
    def validate_name(self, value):
        """
        验证设备名称字段
        """
        if not value or not value.strip():
            raise serializers.ValidationError("设备名称不能为空")
        return value.strip()
    
    def validate_experiment(self, value):
        """
        验证相关试验字段
        """
        if not value or not value.strip():
            raise serializers.ValidationError("相关试验不能为空")
        return value.strip()
    
    def validate_responsible(self, value):
        """
        验证设备负责人字段
        """
        if not value or not value.strip():
            raise serializers.ValidationError("设备负责人不能为空")
        return value.strip()